//
// Created by ziya on 2021/10/18.
//

#include "hpp/ThreadPool.h"
#include "hpp/TaskPool.h"

TaskPool taskpool;

ThreadPool::ThreadPool(int coreSize, int maxSize) : _core_size(coreSize),
                                                    _max_size(maxSize),
                                                    _live_size(coreSize),
                                                    _busy_size(0){

    _thread_ids = static_cast<JavaThread **>(calloc(_max_size, sizeof(JavaThread *)));

    assert( pthread_mutex_init(_lock,NULL) ==0,"mutex init fail");

    assert(pthread_cond_init(_condt,NULL) ==0,"mutex init fail");

    for (int i = 0; i < coreSize; ++i) {

        JavaThread* jt = new JavaThread(i);
        jt->run();
    }

}

void ThreadPool::expand() {

    for (int i = _live_size; i < _max_size; ++i) {
        JavaThread* t = new JavaThread(i);

        _thread_ids[i] = t;

        t->run();

        _live_size++;
    }


}

void ThreadPool::shrink() {
    for (int i = 0; i < _max_size - _core_size; ++i) {
        pthread_cond_signal(taskpool._condt);
    }
}
